package io.github.siltal.examsystembackend.service.impl;

import io.github.siltal.examsystembackend.dto.*;
import io.github.siltal.examsystembackend.entity.ExamHistory;
import io.github.siltal.examsystembackend.entity.ExamOption;
import io.github.siltal.examsystembackend.entity.ExamQuestion;
import io.github.siltal.examsystembackend.repository.ExamHistoryRepository;
import io.github.siltal.examsystembackend.repository.ExamOptionRepository;
import io.github.siltal.examsystembackend.repository.ExamQuestionRepository;
import io.github.siltal.examsystembackend.service.QuestionOptionService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class QuestionOptionServiceImpl implements QuestionOptionService {
    private final ExamQuestionRepository examQuestionRepository;
    private final ExamOptionRepository examOptionRepository;
    private final ExamHistoryRepository examHistoryRepository;

    private final Integer TOTAL_QUESTIONS = 800;


    public QuestionOptionServiceImpl(
            ExamQuestionRepository examQuestionRepository,
            ExamOptionRepository examOptionRepository, ExamHistoryRepository examHistoryRepository
    ) {
        this.examQuestionRepository = examQuestionRepository;
        this.examOptionRepository = examOptionRepository;

        this.examHistoryRepository = examHistoryRepository;
    }


    @Override
    public List<ExamQuestion> getAllQuestions() {
        return examQuestionRepository.findAll();
    }

    @Override
    public Optional<ExamQuestion> getQuestionById(Integer id) {
        return examQuestionRepository.findById(id);
    }

    /**
     * 随机获取指定数量的题目，并转换为 RandomQuestionOptionResponse DTO。
     *
     * @param size 需要获取的题目数量
     * @return RandomQuestionOptionResponse 包装的列表
     */
    public RandomQuestionOptionResponse getRandomQuestionOption(Integer size) {
        // 边界情况处理：如果数据库中没有题目，直接返回空列表
        if (TOTAL_QUESTIONS == 0) {
            return RandomQuestionOptionResponse.empty();
        }

        // 边界情况处理：如果请求的数量大于总数，则调整为总数
        if (size > TOTAL_QUESTIONS) {
            size = TOTAL_QUESTIONS;
        }

        List<QuestionOption> questionOptions = new ArrayList<>(size);
        Set<Integer> usedQuestionIds = new HashSet<>(size);//去重
        Random random = ThreadLocalRandom.current();

        while (questionOptions.size() < size) {
            Integer randomId = random.nextInt(TOTAL_QUESTIONS) + 1;
            if (usedQuestionIds.contains(randomId)) {
                continue;
            }
            Optional<ExamQuestion> optionalQuestion = examQuestionRepository.findById(randomId);
            optionalQuestion.ifPresent(question -> {
                usedQuestionIds.add(question.getId());
                List<ExamOption> options = examOptionRepository.findByQuestionId(question.getId());
                questionOptions.add(QuestionOption.from(question, options));
            });
        }

        return RandomQuestionOptionResponse.from(questionOptions);
    }

    @Override
    public ExamHistorySubmitResponse examHistorySubmit(ExamHistorySubmitRequest submit) {
        ExamHistory examHistory = new ExamHistory(submit);
        examHistoryRepository.save(examHistory);

        return ExamHistorySubmitResponse.success();
    }

    @Override
    public ExamHistoryFetchResponse examHistoryFetch(ExamHistoryFetchRequest fetchRequest) {
        List<ExamHistory> byUserId = examHistoryRepository.findByUserId(fetchRequest.id());
        List<ExamHistoryItem> examHistoryItems = byUserId.stream().map((ExamHistoryItem::from)).toList();

        return ExamHistoryFetchResponse.from(examHistoryItems);

    }


}